package services.api;

import dto.api.*;
import models.application.*;
import models.pubobj.AniObjectState;
import models.user.*;
import org.apache.commons.lang3.*;
import play.db.ebean.Transactional;
import services.AniPublicPropService;
import services.application.AniAppQueryService;
import services.exception.AniDataException;
import utils.*;

import java.util.*;

public class AniApiRegisterService extends AniApiService {
    @Transactional
    public static void registerApi(Map<String, String> apiRegInfoArgs, AniUser curUser) throws Exception {
        //save api info
        MVCUtils.verifyRequiredElements(apiRegInfoArgs, ApiInputInfoDto.requiredRegisterFieldKeys);
        ApiInputInfoDto oneApiInputInfoDto = new ApiInputInfoDto(
                apiRegInfoArgs,
                AniPublicPropService.getObjectStateWithIdOrName(AniObjectState.States.DISABLED.name())
        );
        AniApp curApp = AniAppQueryService.getApp(oneApiInputInfoDto.getHostAppDao());
        checkApiRegisterElements(oneApiInputInfoDto, curApp, curUser);
        AniApi curApi = saveApiRegisterInfo(oneApiInputInfoDto, curApp);

        //save api-params info
        if(!StringUtils.isEmpty(oneApiInputInfoDto.params)){
            System.out.println(oneApiInputInfoDto.params);
            List<ApiParamDto> apiParams = ApiParamDto.generateFromJsonArrayStr(oneApiInputInfoDto.params, curApi);
            try{
                AniApiEditService.saveApiParamsInfo(apiParams, curApi);
            }catch (Exception e){
                curApi.delete();
                throw e;
            }
        }

    }
    private static AniApi saveApiRegisterInfo(ApiInputInfoDto oneApiInfo, AniApp curApp){
        AniApi oneApi = oneApiInfo.generateDao(curApp);
        oneApi.state = AniPublicPropService.getObjectStateWithIdOrName(AniObjectState.States.DISABLED.name());
        try{
            oneApi.save();
        } catch (Exception e){
            throw new AniDataException("API_REGISTER_INFO_SAVING_FAILED");
        }
        return oneApi;
    }
}
